import tkinter as tk
from tkinter.filedialog import *
from tkinter import ttk
import final
import cv2
from PIL import Image, ImageTk
import time


class Surface(ttk.Frame):
    img_path = ""
    h = 600
    w = 600

    def __init__(self, win):
        ttk.Frame.__init__(self, win)
        # UI页面设计
        frame_left = ttk.Frame(self)
        frame_right = ttk.Frame(self)
        frame_right_bt = ttk.Frame(self)
        win.title("车牌识别")
        win.state("zoomed")
        self.pack(fill=tk.BOTH, expand=tk.YES, padx="5", pady="5")
        frame_left.pack(side=LEFT, expand=1, fill=BOTH)
        frame_right.pack(side=TOP, expand=1, fill=tk.Y)
        frame_right_bt.pack(side=RIGHT, expand=0)

        ttk.Label(frame_left, text='原图：').pack(anchor="nw")
        self.raw_image = ttk.Label(frame_left)
        self.raw_image.pack(anchor="nw")

        ttk.Label(frame_right, text='车牌位置：').grid(column=0, row=0, sticky=tk.W)
        self.plate = ttk.Label(frame_right)
        self.plate.grid(column=0, row=1, sticky=tk.W)

        ttk.Label(frame_right, text='识别结果：').grid(column=0, row=2, sticky=tk.W)
        self.res = ttk.Label(frame_right, text="")
        self.res.grid(column=0, row=3, sticky=tk.W)

        ttk.Label(frame_right, text='识别用时：').grid(column=0, row=4, sticky=tk.W)
        self.running_time = ttk.Label(frame_right, text="")
        self.running_time.grid(column=0, row=5, sticky=tk.W)

        pic = ttk.Button(frame_right_bt, text="选择图片", width=20, command=self.recognize)
        pic.pack(anchor="se", pady="6")

    def get_imgtk(self, img_bgr):
        # 格式转换和图片大小转换，避免超出屏幕大小
        img = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
        im = Image.fromarray(img)
        imgtk = ImageTk.PhotoImage(image=im)
        width = imgtk.width()
        height = imgtk.height()
        if width > self.w or height > self.h:
            width_factor = self.w / width
            height_factor = self.h / height
            factor = min(width_factor, height_factor)

            width = int(width * factor)
            if width <= 0:
                width = 1
            height = int(height * factor)
            if height <= 0:
                height = 1
            im = im.resize((width, height), Image.ANTIALIAS)
            imgtk = ImageTk.PhotoImage(image=im)
        return imgtk

    def show_card(self, card, text):
        if (card.any()):
            # 转换图片格式
            card = cv2.cvtColor(card, cv2.COLOR_BGR2RGB)
            card = Image.fromarray(card)
            self.imgtk_card = ImageTk.PhotoImage(image=card)
            self.plate.configure(image=self.imgtk_card, state='enable')
            if (text == ""):
                text = "OCR无法识别车牌"
            self.res.configure(text=str(text))
        else:
            text = "无法定位车牌"
            self.plate.configure(image=self.imgtk_card, state='disable')
            self.res.configure(text=str(text))

    def recognize(self):
        # 支持jpg和png格式
        self.img_path = askopenfilename(title="选择识别图片", filetypes=[("jpg图片", "*.jpg"), ("png图片", "*.png")])
        if self.img_path:
            img = final.imreadex(self.img_path)
            self.imgtk = self.get_imgtk(img)
            self.raw_image.configure(image=self.imgtk)

            st = time.time()
            card, text = final.predict(img)
            ed = time.time()

            # 显示识别用时
            self.running_time.configure(text=str(round(ed - st, 3))+"s")
            self.show_card(card, text)


if __name__ == '__main__':
    LPR = tk.Tk()
    surface = Surface(LPR)
    LPR.mainloop()
